package se.perp.c4.control;

import java.util.ArrayList;
import java.util.List;
import se.perp.c4.control.iface.IMoveListener;
import se.perp.c4.control.iface.IPieceSelectionListener;
import se.perp.c4.control.iface.ISpecialCardListener;
import se.perp.c4.model.Actor;
import se.perp.c4.model.Actor.EActor;
import se.perp.c4.model.ActorCollection;
import se.perp.c4.model.Move;
import se.perp.c4.model.Territory;
import se.perp.c4.model.Territory.ETerritory;
import se.perp.c4.model.TerritoryCollection;
import se.perp.c4.ui.GamePiece;
import se.perp.c4.ui.PieceCollection;
import se.perp.c4.ui.PieceOrderer;
import se.perp.c4.ui.SpecialCard;

class RecallToMordorHandler implements IPieceSelectionListener, ISpecialCardListener {

    private TerritoryCollection terrColl;
    private ActorCollection actorColl;
    private PieceCollection pieceColl;
    private IMoveListener moveCompleteListener;

    public RecallToMordorHandler(ActorCollection ac, TerritoryCollection tc, PieceCollection pc, IMoveListener l ) {
        actorColl = ac;
        terrColl = tc;
        pieceColl = pc;
        moveCompleteListener = l;
    }

    public void pieceSelected(EActor ea) {
        Actor a = actorColl.get(ea);
        ETerritory from = a.where;
        terrColl.moveActor(a, Territory.ETerritory.MORDOR);
        PieceOrderer.orderAll(terrColl, pieceColl);

        pieceColl.setPieceSelectionListener(null);
        pieceColl.exitPieceSelectionMode();

        GamePiece gp = pieceColl.get(ea);
        gp.setNormalBackground();

        Move move = new Move(ea, EActor.NOBODY, from, ETerritory.MORDOR);
       
        moveCompleteListener.recallMoveMade(move);
    }

    public void cardClicked(SpecialCard c) {

        List<EActor> recallable = new ArrayList<EActor>();

        for (Territory t : terrColl) {
            if (t.isOccupiedByDark() && t.which != ETerritory.MORDOR) {
                for (Actor a : t.getOccupants()) {
                    recallable.add(a.who);
                }
            }
        }

        if (recallable.isEmpty()) {
            throw new RuntimeException("Erroneous invocation of Recall to Mordor!");
        }

        pieceColl.setPieceSelectionListener(this);
        pieceColl.enterPieceSelectionMode(recallable);
        c.setEnabled(false);
    }
}
